from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from apps.meiduo_admin.serializers.sku import SKUSerializer, GoodsCategorySerializer, SPUSerializer, \
    SpecsModelSerializer
from apps.meiduo_admin.utils import PageNum


class SKUModelViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]
    serializer_class = SKUSerializer
    # queryset = SKU.objects.all()
    pagination_class = PageNum

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return SKU.objects.filter(name__contains=keyword)

        return SKU.objects.all()


class GoodsCategoryListAPIView(ListAPIView):
    # 获取所有三级分类信息
    queryset = GoodsCategory.objects.filter(subs=None)

    serializer_class = GoodsCategorySerializer


class SPUListAPIView(ListAPIView):
    # 获取所有SPU信息
    queryset = SPU.objects.all()
    serializer_class = SPUSerializer


class SPUSpecificationAPIView(APIView):
    def get(self, request, spu_id):
        # 获取到该spu的详细规格
        specs = SPUSpecification.objects.filter(spu_id=spu_id)
        # 传入序列化器
        specsSerializer = SpecsModelSerializer(specs, many=True)
        # 返回响应
        return Response(specsSerializer.data)
